package com.framework.auth.config;

import com.framework.authorization.vo.UserDetailsVo;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Optional;

/**
 * @author zhoubb
 * @version V1.0
 * @Date 2020/4/12 18:42
 * @since JDK 1.8
 */
public class UserTokenEnhancer implements TokenEnhancer {

    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {

        DefaultOAuth2AccessToken token= (DefaultOAuth2AccessToken) accessToken;
        Map<String, Object> additionalInformation = new LinkedHashMap<String, Object>();
//        UserDetailsVo userDetails = (UserDetailsVo)authentication.getUserAuthentication().getPrincipal();
// //       Optional<? extends GrantedAuthority> role = userDetails.getAuthorities().stream().findFirst();
//        additionalInformation.put("openId", userDetails.getOpenId());
////        additionalInformation.put("roleId", RoleTypeEnum.getValue(role.get().getAuthority()));
//        additionalInformation.put("nickname", userDetails.getNickname());
//        additionalInformation.put("avatarUrl", userDetails.getAvatarUrl());
//        additionalInformation.put("gender", userDetails.getGender());
////        additionalInformation.put("phoneNumber", userDetails.getPhoneNumber());
//        additionalInformation.put("authorize", userDetails.getAuthorize());
//        token.setAdditionalInformation(additionalInformation);

        //UserTtzDetailsVo userDetails = (UserTtzDetailsVo)authentication.getUserAuthentication().getPrincipal();
        UserDetailsVo userDetails = (UserDetailsVo)authentication.getUserAuthentication().getPrincipal();
        Optional<GrantedAuthority> role = userDetails.getAuthorities().stream().findFirst();
        additionalInformation.put("id", userDetails.getUsername());
        additionalInformation.put("roleId", role.get().getAuthority());
        //additionalInformation.put("roleId", 0);
        token.setAdditionalInformation(additionalInformation);
        return accessToken;
    }
}
